package learnning.dao.base;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;

public abstract class HibernateDao {
	private static final SessionFactory sessionFactory = new AnnotationConfiguration()
			.configure().buildSessionFactory();
	@SuppressWarnings("rawtypes")
	private static final ThreadLocal session = new ThreadLocal();

	@SuppressWarnings("unchecked")
	public static Session getSession() {
		Session session = (Session) HibernateDao.session.get();
		if (session == null) {
			session = sessionFactory.openSession();
			HibernateDao.session.set(session);
		}
		return session;
	}

	public void begin() {
		getSession().beginTransaction();
	}

	public void commit() {
		getSession().getTransaction().commit();
	}

	@SuppressWarnings("unchecked")
	public void rollback() {
		try {
			getSession().getTransaction().rollback();
		} catch (HibernateException e) {
			System.out.println("không thể rollback");
		}
		try {
			getSession().close();
		} catch (HibernateException e) {
			System.out.println("không thể đóng session");
		}
		HibernateDao.session.set(null);
	}

	@SuppressWarnings("unchecked")
	public void close() {
		getSession().close();
		HibernateDao.session.set(null);
	}
}
